package com.credithc.signature.core.rabbitmq;

import com.credithc.signature.common.ro.core.CoreRequet;
import com.credithc.signature.core.service.CoreHandler;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
public class RetryConsumer {

    @Autowired
    CoreHandler coreHandler;


    @RabbitListener(queues = "core_process_queue", containerFactory = "rabbitListenerContainerFactory")
    public void processCoreDelayMessage(@Payload CoreRequet coreRequet, @Headers Map<String, Object> headers, Message message, Channel channel) throws IOException {
        log.info("接收到Core延迟队列消息id:{}", message.getMessageProperties().getDeliveryTag());
        try {
            log.info("接收到延迟队列消息流水:{}", coreRequet.getRequestSn());
            log.debug("CallbackReq = " + coreRequet.toString());
            // 确认消息成功接收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            coreHandler.handle(coreRequet);
        } catch (Throwable e) {
            log.error("延迟队列－消息－:requestSn={},处理失败...... ", message.getMessageProperties().getDeliveryTag(), e);
            //说明消息处理异常，但是不能重新放入队列，否则变成死循环。
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
